package com.vng.zini.gifapp.components;

import java.io.IOException;

import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;

public class GIFMediaRecorder {
	Camera myCamera;
	MediaRecorder mediaRecorder;
	private MyCameraSurfaceView myCameraSurfaceView;
	public GIFMediaRecorder(MyCameraSurfaceView _myCameraSurfaceView,Camera _myCamera){
		myCamera = _myCamera;
		myCameraSurfaceView = _myCameraSurfaceView;
	}
	public boolean prepareMediaRecorder() {
		myCamera = GIFCamera.getCameraInstance();
		mediaRecorder = new MediaRecorder();

		myCamera.unlock();
		mediaRecorder.setCamera(myCamera);

		mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
		mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
		// mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

		mediaRecorder.setProfile(CamcorderProfile
				.get(CamcorderProfile.QUALITY_HIGH));
		mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
		Camera.Size bestSize = GIFCamera.getBestSize();
		System.out.println(bestSize.width);
		System.out.println(bestSize.height);
		mediaRecorder.setVideoSize(bestSize.width, bestSize.height);
		mediaRecorder.setVideoFrameRate(3);

		mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder()
				.getSurface());

		try {
			mediaRecorder.prepare();
		} catch (IllegalStateException e) {
			releaseMediaRecorder();
			return false;
		} catch (IOException e) {
			releaseMediaRecorder();
			return false;
		}
		return true;

	}
	
	public void releaseMediaRecorder() {
		if (mediaRecorder != null) {
			mediaRecorder.reset(); // clear recorder configuration
			mediaRecorder.release(); // release the recorder object
			mediaRecorder = null;
			myCamera.release();
			//myCamera.lock(); // lock camera for later use
		}
	}
	public void stop(){
		mediaRecorder.stop();
	}
	
	public void start(){
		mediaRecorder.start();
	}
}
